package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.common.dto.UserDTO;
import com.example.domain.User;
import com.example.domain.WalletRecord;
import com.example.service.UserService;
import com.example.service.WalletRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class WalletController {

	private final WalletRecordService walletRecordService;

	private final UserService userService;

	@Autowired
	public WalletController(WalletRecordService walletRecordService, UserService userService) {
		this.walletRecordService = walletRecordService;
		this.userService = userService;
	}

	/**
	 * 根据用户id查询充值记录
	 *
	 * @param userId 用户id
	 * @return 返回的JSON字符串
	 */
	@PostMapping(value = "/user/wallet/select/user", produces = "application/json;charset=utf-8")
	public String getUserWalletInfo(Integer userId) {
		Map<String, Object> message = new HashMap<>(16);

		//查询支付记录
		List<WalletRecord> walletByUserId = walletRecordService.getWalletByUserId(userId);
		message.put("walletRecords", walletByUserId);
		return JSON.toJSONString(message);
	}

	/**
	 * 用户充值
	 *
	 * @param walletRecord 包含topUpMoney、UserId信息
	 * @return 返回的JSON字符串
	 */
	@PostMapping(value = "/user/wallet/update/user", produces = "application/json;charset=utf-8")
	public String insertWalletRecordByUserId(@RequestBody WalletRecord walletRecord) {
		HashMap<String, Object> message = new HashMap<>(16);

		//新增充值记录
		walletRecordService.save(walletRecord);
		message.put("message", 1);

		//更新用户余额
		User user = userService.getById(walletRecord.getUserId());
		user.setBalance(user.getBalance() + walletRecord.getMoney());
		userService.updateById(user);
		message.put("user", user);

		return JSON.toJSONString(message);
	}

	/**
	 * 用户支付
	 *
	 * @return
	 */
	@PostMapping(value = "/user/pay", produces = "application/json;charset=utf-8")
	public String payMoney(@RequestBody UserDTO userDTO) {
		HashMap<String, Object> message = new HashMap<>(16);

		User user = userService.getById(userDTO.getId());
		int identityPrice = user.getIntegral() / 100;

		//用户所需支付的金额（减去积分抵扣）
		double price = userDTO.getBalance() - identityPrice;
		user.setBalance(user.getBalance() - price);
		user.setIntegral(user.getIntegral() - identityPrice * 100 + (int) price);
		userService.updateById(user);

		//新增支付记录
		WalletRecord walletRecord = new WalletRecord();
		walletRecord.setUserId(userDTO.getId());
		walletRecord.setMoney(price);
		walletRecord.setIdentity(1);
		walletRecordService.save(walletRecord);

		message.put("message", 1);
		return JSON.toJSONString(message);
	}

}
